package com.link2room.quintesson.service.impl;

import com.link2room.common.constant.DefaultValue;
import com.link2room.common.exception.SysException;
import com.link2room.common.util.ClassConverUtil;
import com.link2room.common.util.DateUtil;
import com.link2room.common.util.JacksonUtil;
import com.link2room.common.util.StringUtil;
import com.link2room.enums.exception.QuintessonSysExceptionEnum;
import com.link2room.optimus.dto.result.base.L2REverydayPriceAndStockDto;
import com.link2room.optimus.dto.result.base.L2REverydayPriceDto;
import com.link2room.optimus.dto.result.base.L2REverydayStockDto;
import com.link2room.optimus.dto.result.base.TaobaoXrateplanDto;
import com.link2room.quintesson.dto.result.base.TaobaoXrateplanHotelDto;
import com.link2room.quintesson.dto.result.manager.*;
import com.link2room.quintesson.exception.TaobaoException;
import com.link2room.quintesson.service.ITaobaoAPIService;
import com.link2room.quintesson.util.TaobaoUtil;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.*;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service("taobaoAPIService")
public class TaobaoAPIServiceImpl implements ITaobaoAPIService {

	/**
	 * 酒店上传
	 */
	@Override
	public TaobaoXhotelDto syncTaobaoXhotel(TaobaoXhotelDto taobaoXhotelDto) throws Exception {
		String lhotelGroupCode=taobaoXhotelDto.getLhotelGroupCode();
		String sessionKey=TaobaoUtil.getTaobaoSessionKey(lhotelGroupCode);
		XhotelUpdateRequest req = ClassConverUtil.copyProperties(taobaoXhotelDto, XhotelUpdateRequest.class);
		req.setOuterId(taobaoXhotelDto.getOuterHid());
		if(StringUtil.isNotBlank(req.getLatitude())){
			if(req.getLatitude().length()>8){
				req.setLatitude(req.getLatitude().substring(0,8));
			}
		}
		if(StringUtil.isNotBlank(req.getLongitude())){
			if(req.getLongitude().length()>9){
				req.setLongitude(req.getLongitude().substring(0,9));
			}
		}
		req.setPositionType("A");
		//请求同步
		TaobaoClient client= TaobaoUtil.getTaobaoClient(lhotelGroupCode);
		XhotelUpdateResponse response = client.execute(req,sessionKey);
		//判断请求返回结果
        if(response.getXhotel()==null){
			XhotelGetRequest rhreq=new XhotelGetRequest();
			rhreq.setOuterId(taobaoXhotelDto.getOuterHid());
			XhotelGetResponse rhres=client.execute(rhreq,sessionKey);
			if(rhres.getXhotel()!=null){
				XHotel xhotel = rhres.getXhotel();
				this.setTaobaoXhotel(xhotel,taobaoXhotelDto);
			}else{
				throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_UPHOTEL, response.getSubCode()+":"+response.getSubMsg());
			}
        }else{
          	XHotel xhotel = response.getXhotel();
			this.setTaobaoXhotel(xhotel,taobaoXhotelDto);
        }
		return taobaoXhotelDto;
	}

	private void setTaobaoXhotel(XHotel xhotel,TaobaoXhotelDto taobaoXhotelDto){
		Long matchStatus=xhotel.getMatchStatus();
		taobaoXhotelDto.setMatchStatus(matchStatus);
		taobaoXhotelDto.setMatchInfo(TaobaoUtil.getMatchInfo(matchStatus.intValue()));
		taobaoXhotelDto.setHid(xhotel.getHid());
		taobaoXhotelDto.setStatus(xhotel.getStatus());
		taobaoXhotelDto.setTaobaoCreatedTime(xhotel.getCreatedTime());
		taobaoXhotelDto.setTaobaoModifiedTime(xhotel.getModifiedTime());
		SHotel sHotel = xhotel.getsHotel();
		TaobaoShotelDto taobaoShotelDto=ClassConverUtil.copyProperties(taobaoXhotelDto,TaobaoShotelDto.class);
		taobaoShotelDto.setId(null);
		taobaoShotelDto.setShotel(JacksonUtil.beanToJson(sHotel));
		taobaoXhotelDto.setTaobaoShotelDto(taobaoShotelDto);
	}

	private void setTaobaoXroomtype(XRoomType xRoomType,TaobaoXroomtypeDto taobaoXroomtypeDto){
		Long matchStatus=xRoomType.getMatchStatus();
		taobaoXroomtypeDto.setArea(xRoomType.getArea());
		taobaoXroomtypeDto.setRid(xRoomType.getRid());
		taobaoXroomtypeDto.setMatchStatus(xRoomType.getMatchStatus());
		taobaoXroomtypeDto.setOuterRid(xRoomType.getOuterId());
		taobaoXroomtypeDto.setName(xRoomType.getName());
		taobaoXroomtypeDto.setMatchInfo(TaobaoUtil.getMatchInfo(matchStatus.intValue()));
		SRoomType sRoomType = xRoomType.getsRoomtype();
		TaobaoSroomtypeDto taobaoSroomtypeDto=ClassConverUtil.copyProperties(taobaoXroomtypeDto,TaobaoSroomtypeDto.class);
		taobaoSroomtypeDto.setId(null);
		taobaoSroomtypeDto.setSrmtype(JacksonUtil.beanToJson(sRoomType));
		taobaoXroomtypeDto.setTaobaoSroomtypeDto(taobaoSroomtypeDto);
	}

	/**
	 * 房型更新
	 */
	@Override
	public TaobaoXroomtypeDto syncTaobaoXroomtype(TaobaoXroomtypeDto taobaoXroomtypeDto) throws Exception {
		String lhotelGroupCode=taobaoXroomtypeDto.getLhotelGroupCode();
		String sessionKey=TaobaoUtil.getTaobaoSessionKey(lhotelGroupCode);
		XhotelRoomtypeUpdateRequest req = ClassConverUtil.copyProperties(taobaoXroomtypeDto, XhotelRoomtypeUpdateRequest.class);
		if(taobaoXroomtypeDto.getMaxOccupancy() == null || taobaoXroomtypeDto.getMaxOccupancy().intValue() == 0){//默认最大入住2人
			req.setMaxOccupancy(2L);
		}
		req.setHotelCode(taobaoXroomtypeDto.getLhotelCode());
		req.setOuterId(taobaoXroomtypeDto.getOuterRid());
		TaobaoClient client= TaobaoUtil.getTaobaoClient(lhotelGroupCode);
		XhotelRoomtypeUpdateResponse response = client.execute(req, sessionKey);
		//判断请求返回结果
		if(response.getXroomtype()==null){
			//请求查询淘宝接口看需上传的是否存在
			XhotelRoomtypeGetRequest rmreq=new XhotelRoomtypeGetRequest();
			rmreq.setOuterId(taobaoXroomtypeDto.getOuterRid());
			XhotelRoomtypeGetResponse rmres=client.execute(rmreq,sessionKey);
			if(rmres.getXroomtype()!=null){
				 XRoomType xRoomType = rmres.getXroomtype();
				 this.setTaobaoXroomtype(xRoomType,taobaoXroomtypeDto);
			}else{
				throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_UPROOM,taobaoXroomtypeDto.getOuterRid()+"||"+response.getSubCode()+":"+response.getSubMsg());
			}
        }else{
        	 XRoomType xRoomType = response.getXroomtype();
			this.setTaobaoXroomtype(xRoomType,taobaoXroomtypeDto);

		}
		return taobaoXroomtypeDto;
	}

	/**
	 * 价格计划上传
	 */
	@Override
	public TaobaoXrateplanHotelDto syncTaobaoXrateplan(TaobaoXrateplanHotelDto taobaoXrateplanHotelDto, TaobaoXrateplanDto taobaoXrateplanDto) throws Exception {
		//设置请求条件
		String lhotelGroupCode=taobaoXrateplanHotelDto.getLhotelGroupCode();
		String sessionKey=TaobaoUtil.getTaobaoSessionKey(lhotelGroupCode);
		XhotelRateplanUpdateRequest req = ClassConverUtil.copyProperties(taobaoXrateplanDto, XhotelRateplanUpdateRequest.class);
		req.setRateplanCode(taobaoXrateplanHotelDto.getHotelRpCode());
		req.setStatus(taobaoXrateplanHotelDto.getStatus());
		req.setCancelPolicy(this.getCancelPolicy(taobaoXrateplanDto));
		if(taobaoXrateplanDto.getMaxDays() != null && taobaoXrateplanDto.getMaxDays() > 90){
			req.setMaxDays(90L);
		}
		TaobaoClient client= TaobaoUtil.getTaobaoClient(lhotelGroupCode);
		XhotelRateplanUpdateResponse response = client.execute(req, sessionKey);
		//判断请求返回结果
		XhotelRateplanGetRequest rmreq=new XhotelRateplanGetRequest();
		rmreq.setRateplanCode(taobaoXrateplanHotelDto.getHotelRpCode());
		XhotelRateplanGetResponse rares=client.execute(rmreq,sessionKey);
		if(response.getRpid()==null){
			//请求查询淘宝接口看需上传的是否存在
			if(StringUtil.isNotBlank(response.getErrorCode())){
				throw new SysException(QuintessonSysExceptionEnum.TAOBAO_UPRATEPLAN, taobaoXrateplanDto.getRpCode()+"||"+response.getSubCode()+":"+response.getSubMsg());
			}else {
				if(rares.getRateplan()!=null){
					RatePlan ratePlan = rares.getRateplan();
					taobaoXrateplanHotelDto.setRpid(ratePlan.getRpid());
					taobaoXrateplanHotelDto.setStatus(ratePlan.getStatus());
					taobaoXrateplanHotelDto.setMatchStatus(5L);
					taobaoXrateplanHotelDto.setMatchInfo(TaobaoUtil.getMatchInfo(5));
				}else{
					throw new SysException(QuintessonSysExceptionEnum.TAOBAO_UPRATEPLAN, taobaoXrateplanDto.getRpCode()+"||"+response.getSubCode()+":"+response.getSubMsg());
				}
			}
        }else{
			taobaoXrateplanHotelDto.setMatchStatus(5L);
			taobaoXrateplanHotelDto.setMatchInfo(TaobaoUtil.getMatchInfo(5));
			taobaoXrateplanHotelDto.setRpid(response.getRpid());
			taobaoXrateplanHotelDto.setStatus(rares.getRateplan().getStatus());
        }
		return taobaoXrateplanHotelDto;
	}

	/**
	 * 商品上传
	 */
	@Override
	public TaobaoXrateDto syncTaobaoXrate(TaobaoXrateDto taobaoXrateDto,
										  TaobaoXrateInventoryDto taobaoXrateInventoryDto,
										  List<Map<String, String>> rateSwitchCal) throws Exception {
		String lhotelGroupCode=taobaoXrateDto.getLhotelGroupCode();
		String sessionKey=TaobaoUtil.getTaobaoSessionKey(lhotelGroupCode);
		XhotelRateUpdateRequest req = ClassConverUtil.copyProperties(taobaoXrateDto, XhotelRateUpdateRequest.class);
		req.setRateplanCode(taobaoXrateDto.getHotelRpCode());
		req.setOutRid(taobaoXrateDto.getRmtype());
		//开关状态转化为json
		String rateSwitchCalStr = JacksonUtil.beanToJson(rateSwitchCal);
		req.setRateSwitchCal(rateSwitchCalStr);
		if(taobaoXrateInventoryDto != null){
			String inventory=JacksonUtil.beanToJson(taobaoXrateInventoryDto);
			req.setInventoryPrice(inventory);
		}
		TaobaoClient client= TaobaoUtil.getTaobaoClient(lhotelGroupCode);
		//请求同步
		XhotelRateUpdateResponse response = client.execute(req , sessionKey);
		//判断请求返回结果
		if(response.getGidAndRpid()!=null){
			taobaoXrateDto.setGidRpid(response.getGidAndRpid());
			taobaoXrateDto.setMatchStatus(5L);
			taobaoXrateDto.setMatchInfo(TaobaoUtil.getMatchInfo(5));
		}else{
			//请求查询淘宝接口看需上传的是否存在
			XhotelRateGetRequest rateReq=new XhotelRateGetRequest();
			rateReq.setRateplanCode(taobaoXrateDto.getHotelRpCode());
			rateReq.setOutRid(taobaoXrateDto.getRmtype());
			XhotelRateGetResponse rateRes=client.execute(rateReq , sessionKey);
			if(rateRes.getRate()!=null){
				taobaoXrateDto.setGidRpid(response.getGidAndRpid());
				taobaoXrateDto.setMatchStatus(5L);
				taobaoXrateDto.setMatchInfo(TaobaoUtil.getMatchInfo(5));
			}else{
				throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_UPRATE,taobaoXrateDto.getMcdCode()+"||"+response.getSubCode()+":"+response.getSubMsg());
			}
		}
		return taobaoXrateDto;
	}

	/**
	 * 批量增量
	 */
	@Override
	public void syncTaobaoXratesIncrementRequest(String lhotelGroupCode,
			List<TaobaoRateInventoryPriceMap> taobaoRateInventoryPriceMapList) throws Exception {
		String sessionKey=TaobaoUtil.getTaobaoSessionKey(lhotelGroupCode);
		int capability = 10;//分组每组容量
		//分批次处理 10 个一组
		int count = taobaoRateInventoryPriceMapList.size()/capability;
		int mod = taobaoRateInventoryPriceMapList.size()%capability;
		List<TaobaoRateInventoryPriceMap> subList = null;
		StringBuffer sb=new StringBuffer();
		TaobaoClient client= TaobaoUtil.getTaobaoClient(lhotelGroupCode);
		for(int i = 0  ; i <= count ; i ++ ){
			if(i == count){
				subList = taobaoRateInventoryPriceMapList.subList(i*capability, i*capability+mod);
			}else{
				subList = taobaoRateInventoryPriceMapList.subList(i*capability, (i+1)*capability);
			}
			if(subList != null && subList.size() >0){
				String rateInventoryPriceMap = JacksonUtil.beanToJson(subList);
				XhotelRatesIncrementRequest req = new XhotelRatesIncrementRequest();
				req.setRateInventoryPriceMap(rateInventoryPriceMap);
				XhotelRatesIncrementResponse response = client.execute(req,sessionKey);
				if(response.getGidAndRpids() == null){
					sb.append(response.getSubMsg());
				}
			}
		}
		if(StringUtil.isNotBlank(sb.toString())){
			throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_UPINCREMENT, sb.toString());
		}
	}

	/**
	 * 组装商品明细
	 * @param l2REverydayPriceAndStockDtoList
	 * @return
	 * @throws Exception
	 */
	@Override
	public TaobaoRateDataDto composeTaobaoRateDataDto(List<L2REverydayPriceAndStockDto> l2REverydayPriceAndStockDtoList) throws Exception {
		List<Map<String, String>> rateSwitchCal=new ArrayList<Map<String,String>>();
		List<Map<String, String>> inventory_price=new ArrayList<Map<String,String>>();
		TaobaoRateDataDto taobaoRateDataDto=new TaobaoRateDataDto();
		try {
			if(l2REverydayPriceAndStockDtoList!=null&&l2REverydayPriceAndStockDtoList.size()>0){
				for(L2REverydayPriceAndStockDto trData:l2REverydayPriceAndStockDtoList){
					Map<String, String> mapDetail = new HashMap<String, String>();
					Map<String, String> mapSwitch = new HashMap<String, String>();
					String rsvDateStr = DateUtil.format(trData.getRsvDate(),DateUtil.webFormat);
					mapDetail.put("date", rsvDateStr);
					mapSwitch.put("date", rsvDateStr);
					L2REverydayPriceDto priceDto = trData.getL2REverydayPriceDto();
					L2REverydayStockDto stockDto = trData.getL2REverydayStockDto();

					BigDecimal price = priceDto.getCurrentPrice();
					if(price.compareTo(BigDecimal.ZERO)<=0){
						//价格
						mapDetail.put("price", "999900");
						mapDetail.put("quota", "0");
						//没有价格时。关房
						mapSwitch.put("rate_status", "0");
					}else{
						if(stockDto!=null){
							Integer num= stockDto.getSaleNum();
							if(num<0){
								num=0;
							}
							mapDetail.put("price", price.multiply(new BigDecimal(100)).setScale(0).toString());
							mapDetail.put("quota",num.toString() );
							//开关  0，关闭；1，打开
							mapSwitch.put("rate_status", DefaultValue.F.equalsIgnoreCase(stockDto.getIsClosed())?"1":"0");
						}else {
							mapDetail.put("price", price.multiply(new BigDecimal(100)).setScale(0).toString());
							mapDetail.put("quota", "0");
							//没有价格时。关房
							mapSwitch.put("rate_status", "0");
						}
					}
					rateSwitchCal.add(mapSwitch);
					inventory_price.add(mapDetail);
				}

			}else{
				throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_INVENTORY);
			}
		}catch (Exception e){
			for(int i=0;i<91;i++){
				Map<String, String> mapDetail = new HashMap<String, String>();
				Map<String, String> mapSwitch = new HashMap<String, String>();
				String rsvDateStr= DateUtil.format(DateUtil.addDays(new Date(),i),DateUtil.webFormat);
				mapDetail.put("date", rsvDateStr);
				mapSwitch.put("date", rsvDateStr);
				//价格
				mapDetail.put("price", "999900");
				mapDetail.put("quota", "0");
				//没有价格时。关房
				mapSwitch.put("rate_status", "0");
				rateSwitchCal.add(mapSwitch);
				inventory_price.add(mapDetail);
			}
			throw e;
		}finally {
			taobaoRateDataDto.setRateSwitchCal(rateSwitchCal);
			TaobaoXrateInventoryDto taobaoXrateInventoryDto =new TaobaoXrateInventoryDto();
			taobaoXrateInventoryDto.setInventory_price(inventory_price);
			taobaoXrateInventoryDto.setUse_room_inventory(false);
			taobaoRateDataDto.setTaobaoXrateInventoryDto(taobaoXrateInventoryDto);
			return taobaoRateDataDto;
		}

	}

	/**
	 * 组装增量数据
	 * @param l2REverydayPriceAndStockDtoList
	 * @return
	 */
	@Override
	public TaobaoXrateInventoryDto composeIncrementTaobaoRatedata(List<L2REverydayPriceAndStockDto> l2REverydayPriceAndStockDtoList) throws Exception {
		List<Map<String, String>> inventoryPriceList=new ArrayList<Map<String,String>>();
		try {
			if(l2REverydayPriceAndStockDtoList!=null&&l2REverydayPriceAndStockDtoList.size()>0){
				for(L2REverydayPriceAndStockDto trData:l2REverydayPriceAndStockDtoList){
					Map<String, String> map=new HashMap<String, String>();
					String rsvDateStr = DateUtil.format(trData.getRsvDate(),DateUtil.webFormat);
					map.put("date", rsvDateStr);
					L2REverydayPriceDto priceDto = trData.getL2REverydayPriceDto();
					L2REverydayStockDto stockDto = trData.getL2REverydayStockDto();

					BigDecimal price = priceDto.getCurrentPrice();
					if(price.compareTo(BigDecimal.ZERO)<=0){
						//价格
						map.put("price", "999900");
						map.put("quota", "0");
						//没有价格时。关房
						map.put("status", "0");
					}else{
						Integer num= stockDto.getSaleNum();
						if(num<0){
							num=0;
						}
						map.put("price", price.multiply(new BigDecimal(100)).setScale(0).toString());
						map.put("quota", num.toString());
						//开关  0，关闭；1，打开
						map.put("status", DefaultValue.F.equalsIgnoreCase(stockDto.getIsClosed())?"1":"0");
					}
					inventoryPriceList.add(map);
				}

			}else{
				throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_INVENTORY);
			}
		}catch (Exception e){
			for(int i=0;i<91;i++){
				Map<String, String> map=new HashMap<String, String>();
				String rsvDateStr= DateUtil.format(DateUtil.addDays(new Date(),i),DateUtil.webFormat);
				map.put("date", rsvDateStr);
				//价格
				map.put("price", "999900");
				map.put("quota", "0");
				//没有价格时。关房
				map.put("status", "0");
				inventoryPriceList.add(map);
			}
			throw e;
		}finally {
			TaobaoXrateInventoryDto taobaoXrateInventoryDto =new TaobaoXrateInventoryDto();
			taobaoXrateInventoryDto.setUse_room_inventory(false);
			taobaoXrateInventoryDto.setInventory_price(inventoryPriceList);
			return taobaoXrateInventoryDto;
		}

	}

	/**
	 * 信用住结账
	 * @param lhotelGroupCode
	 * @param terminalNo
	 * @param l2rNo
	 * @param checkOut
	 * @param totalRoomFee
	 * @param otherFee
     * @throws Exception
     */

	@Override
	public void alipayfaceSettle(String lhotelGroupCode,
								 String terminalNo,
								 String l2rNo,
								 Date checkOut,
								 BigDecimal totalRoomFee,
								 BigDecimal otherFee) throws Exception {
		TaobaoClient client= TaobaoUtil.getTaobaoClient(lhotelGroupCode);
		String sessionKey=TaobaoUtil.getTaobaoSessionKey(lhotelGroupCode);

		XhotelOrderAlipayfaceSettleRequest req = new XhotelOrderAlipayfaceSettleRequest();
		if (StringUtil.isNotEmpty(terminalNo)) {
			req.setTid(Long.parseLong(terminalNo));
		} else {
			req.setTid(null);
		}
		if (StringUtil.isNotEmpty(l2rNo)) {
			req.setOutId(l2rNo);
		} else {
			req.setOutId(null);
		}
		req.setCheckOut(checkOut);
		req.setTotalRoomFee(totalRoomFee
				.multiply(new BigDecimal(100)).setScale(0).longValue());
		req.setOtherFee(otherFee.multiply(new BigDecimal(100)).setScale(0)
				.longValue());
		if (otherFee != null
				&& otherFee.compareTo(new BigDecimal("0")) != 0) {
			req.setOtherFeeDetail("{\""
					+ "杂费"
					+ "\":"
					+ otherFee.multiply(new BigDecimal(100)).setScale(0)
					.intValue() + "}");
		}
		XhotelOrderAlipayfaceSettleResponse response =client.execute(req , sessionKey);
		if(!"success".equals(response.getResult())){
			throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_SETTLE_ERROR, "联房单号"+l2rNo+"||"+response.getSubCode()+":"+response.getSubMsg());
		}
	}


	/*
	@Override
	public TaobaoXorder alipayfaceUpdate(TaobaoXorder xorder,TaobaoClient client) throws ApiException {
		   XhotelOrderAlipayfaceUpdateRequest req=new XhotelOrderAlipayfaceUpdateRequest();
		   if(StringUtil.isNotEmpty(xorder.getTid())){
			   req.setTid(Long.parseLong(xorder.getTid()));
		   }else{
			   req.setTid(null);
		   }
		   if(StringUtil.isNotEmpty(xorder.getLkRsvNo())){
			   req.setOutId(xorder.getLkRsvNo());
		   }else{
			   req.setOutId(null);
		   }
		   Long status=null;
		   
	//		   if("order".equals(xorder.getStatus())){
	//			   status=2L;
	//		   }
		   if(TaobaoXorder.STATUS_I.equals(xorder.getStatus())){
			   status=3L;
		   }
		   if(TaobaoXorder.STATUS_O.equals(xorder.getStatus())){
			   status=4L;
		   }
		   if(TaobaoXorder.STATUS_N.equals(xorder.getStatus())){
			   status=5L;
		   }
		   req.setOptType(status);
		   
		   XhotelOrderAlipayfaceUpdateResponse response = client.execute(req , TaobaoConfig.SESSIONKEY);
		   if("success".equals(response.getResult())){
			   if(TaobaoXorder.STATUS_O.equals(xorder.getStatus())){
				   xorder.setResult(TaobaoXorder.RESULT_INCOMPLETE);
			   }else{
				   xorder.setResult(TaobaoXorder.RESULT_SUCCESS);
			   }
		   }else{
			   throw new SysException(BizCodeConstant.TAOBAO_UPRATE, xorder.getLkRsvNo()+"||"
						+xorder.getTid()+"||"+response.getSubCode()+":"+response.getSubMsg());
		   }
		   return xorder;
	}
	

	@Override
	public TaobaoXorder alipayfaceSettle(TaobaoXorder xorder,TaobaoClient client) throws ApiException {
		XhotelOrderAlipayfaceSettleRequest req = new XhotelOrderAlipayfaceSettleRequest();
		if (StringUtil.isNotEmpty(xorder.getTid())) {
			req.setTid(Long.parseLong(xorder.getTid()));
		} else {
			req.setTid(null);
		}
		if (StringUtil.isNotEmpty(xorder.getLkRsvNo())) {
			req.setOutId(xorder.getLkRsvNo());
		} else {
			req.setOutId(null);
		}
		req.setCheckOut(xorder.getCheckOutTime());
		req.setTotalRoomFee(xorder.getTotalRoomFee()
				.multiply(new BigDecimal(100)).setScale(0).longValue());
		req.setOtherFee(xorder.getOtherFee().multiply(new BigDecimal(100)).setScale(0)
				.longValue());
		if (xorder.getOtherFee() != null
				&& xorder.getOtherFee().compareTo(new BigDecimal("0")) != 0) {
			String otherFeeDetail = xorder.getOtherFeeDetail();
			if (StringUtil.isBlank(otherFeeDetail)) {
				otherFeeDetail = "杂费";
			}
			req.setOtherFeeDetail("{\""
					+ otherFeeDetail
					+ "\":"
					+ xorder.getOtherFee().multiply(new BigDecimal(100)).setScale(0)
							.intValue() + "}");
		}
		XhotelOrderAlipayfaceSettleResponse response =client.execute(req , TaobaoConfig.SESSIONKEY);
		if("success".equals(response.getResult())){
			xorder.setResult(response.getResult());
		}else{
			throw new SysException(BizCodeConstant.TAOBAO_UPRATE, xorder.getLkRsvNo()+"||"
					+xorder.getTid()+"||"+response.getSubCode()+":"+response.getSubMsg());
		}
		xorder.setOperate(TaobaoXorder.OPERATE_SETTLE);
		return xorder;
	}
	
	@Override
	public TaobaoXorder alipayfaceCancel(TaobaoXorder xorder,TaobaoClient client) throws ApiException {
		XhotelOrderAlipayfaceCancelsettleRequest req  = new XhotelOrderAlipayfaceCancelsettleRequest();
		if (StringUtil.isNotBlank(xorder.getTid())) {
			req.setTid(Long.parseLong(xorder.getTid()));
		} else {
			req.setTid(null);
		}
		if(StringUtil.isNotBlank(xorder.getCancelReason())){
			req.setReason(xorder.getCancelReason());
		} else {
			req.setReason(null);
		}
		if(StringUtil.isNotBlank(xorder.getLkRsvNo())){
			req.setOutId(xorder.getLkRsvNo());
		}
		//初始化
		XhotelOrderAlipayfaceCancelsettleResponse response = client.execute(req , TaobaoConfig.SESSIONKEY);
		if("success".equals(response.getResult())){
			xorder.setResult(response.getResult());
		}else{
			throw new SysException(BizCodeConstant.TAOBAO_UPRATE, xorder.getLkRsvNo()+"||"
					+xorder.getTid()+"||"+response.getSubCode()+":"+response.getSubMsg());
		}
		xorder.setOperate(TaobaoXorder.OPERATE_SETTLE);
		return xorder;
	}*/

	/*@Override
	public List<TradeRate> getTaobaoTraderates(Date startDate, TaobaoClient client)throws Exception {
		Long pageNo=1L;
		List<TradeRate> tradeRates=new ArrayList<TradeRate>();
		boolean hasNextPage=true;
		while (hasNextPage){
			TraderatesGetRequest req = new TraderatesGetRequest();
			req.setFields("tid,oid,role,rated_nick,nick,result,created,item_title,item_price,content,reply");
			req.setRateType("get");
			req.setRole("buyer");
			req.setUseHasNext(true);
			req.setStartDate(startDate);
			req.setPageNo(pageNo);
			req.setPageSize(40L);
			TraderatesGetResponse response = client.execute(req , TaobaoConfig.SESSIONKEY);
			if (response!=null&&StringUtil.isBlank(response.getErrorCode())){
				hasNextPage=response.getHasNext();
				pageNo++;
				if (response.getTradeRates()!=null&&response.getTradeRates().size()>0){
					tradeRates.addAll(response.getTradeRates());
				}
			}else{
				break;
			}
		}
		return tradeRates;
	}

	@Override
	public Boolean explainTaobaoTraderate(TaobaoTraderates taobaoTraderates, TaobaoClient client)throws Exception {
		TraderateExplainAddRequest req = new TraderateExplainAddRequest();
		req.setOid(taobaoTraderates.getOid());
		req.setReply(taobaoTraderates.getReply());
		TraderateExplainAddResponse response = client.execute(req , TaobaoConfig.SESSIONKEY);
		if(response.getIsSuccess()!=null){
			return response.getIsSuccess();
		}else {
			throw new SysException(BizCodeConstant.TAOBAO_EXPLAINTAOBAOTRADERATE,taobaoTraderates.getOid()+"||"+response.getSubCode()+":"+response.getSubMsg());
		}
	}*/

	private String getCancelPolicy(TaobaoXrateplanDto taobaoXrateplanDto)throws Exception{
		Integer cancelPolicyType = taobaoXrateplanDto.getCancelPolicyType();
		TaobaoCancelPolicyDto taobaoCancelPolicyDto=new TaobaoCancelPolicyDto();
		taobaoCancelPolicyDto.setCancelPolicyType(cancelPolicyType);
		Map<String,Integer> map=null;
		if(4==cancelPolicyType){
			map=new HashMap<>();
			map.put(taobaoXrateplanDto.getCancelPolicyHours(),taobaoXrateplanDto.getCancelPolicyFeeRatio());
		}else if(5==cancelPolicyType){
			map=new HashMap<>();
			map.put("timeBefore",Integer.parseInt(taobaoXrateplanDto.getCancelPolicyHours()));
		}else if(6==cancelPolicyType){
			map=new HashMap<>();
			map.put(taobaoXrateplanDto.getCancelPolicyHours(),taobaoXrateplanDto.getCancelPolicyFeeRatio());
		}
		taobaoCancelPolicyDto.setPolicyInfo(map);
		return JacksonUtil.beanToJson(taobaoCancelPolicyDto);
	}
}
